package com.yicong.ants.ui.scenic;

import static android.app.Activity.RESULT_OK;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.library.baseAdapters.BR;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.adapter.DataBindQuickAdapter;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.view.state.field.FieldStateLayout;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.kennyc.view.MultiStateView;
import com.stay4it.banner.BannerConfig;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.x.livesdk.LiveActivity;
import com.x.livesdk.LiveHot;
import com.x.livesdk.util.http.DataCallBack;
import com.x.livesdk.util.http.HttpUtil;
import com.x.livesdk.util.http.Response;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.find.BannerBean;
import com.yicong.ants.bean.global.ClientConfig;
import com.yicong.ants.bean.home.MallRecommendBean;
import com.yicong.ants.databinding.TourismConfigFragmentBinding;
import com.yicong.ants.manager.AppUpdateManager;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.ad.AntsAdHelper;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ConfigParent;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.holder.BaseViewHolder;
import com.yicong.ants.manager.holder.GlideBannerLoader;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.mvp.adapter.CommonAdapter;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.ui.other.FragmentContainerActivity;
import com.yicong.ants.utils.BitmapUtils;
import com.yicong.ants.utils.PermissionsChecker;
import com.yicong.ants.view.Banner;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zx.sdk.util.ConfigHelper;

import org.apache.commons.lang3.tuple.Triple;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import retrofit2.Call;
import retrofit2.Callback;

/**
 * 旅游主模块， 可以配置  {@link ZzConfigs}
 *
 * @author cchao
 * @version 2019-05-21.
 */
public class TourismConfigFragment extends BaseStatefulFragment<TourismConfigFragmentBinding> implements View.OnClickListener {

    FieldStateLayout mFieldStateLayout;
    DataBindQuickAdapter<MallRecommendBean> mMallAdapter;

    //是否需要记录其实坐标
    private boolean isRecord = true;
    //是否到达底部
    private boolean isBottom = false;
    //是否能够跳转
    private boolean jumpRead = true;
    private float startPosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.tourism_config_fragment;
    }

    @Override
    protected void initEventAndData() {
//        UiHelper.setVisibleElseInVisible(mDataBind.tvFavorite, ZzConfigs.mGlobalCollectFeature);
        initTopGrid();
        initMallAdapter();
        initBanner(mDataBind.banner, null);
        onLoadData();
        mDataBind.setClick(this);
        mDataBind.swipeRefreshLayout.setOnRefreshListener(() -> {
            updateLive();
            mDataBind.swipeRefreshLayout.postDelayed(() -> {
                mDataBind.swipeRefreshLayout.setRefreshing(false);
            }, 1000);
        });

        mDataBind.mScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            float alp = scrollY * 0.02f;
            if (alp < 0) {
                alp = 0;
            } else if (alp > 1) {
                alp = 1;
            }
            mDataBind.imageBar.setAlpha(alp);
            mDataBind.textBar.setAlpha(alp);
            // 滚动到底
            isBottom = scrollY == (((NestedScrollView) v).getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight());
        });

        mDataBind.mScrollView.setOnTouchListener((view, motionEvent) -> {
            if (isBottom) {
                int action = motionEvent.getAction();
                switch (action) {
                    case MotionEvent.ACTION_MOVE:
                        if (isRecord) {
                            startPosition = motionEvent.getRawY();
                            isRecord = false;
                        }
                        if (startPosition - motionEvent.getRawY() > 400 && jumpRead) {
                            jumpRead = false;
                            ZzConfigs.toWebActivityByUrl(mContext, "mall");
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        startPosition = 0;
                        isRecord = true;
                        jumpRead = true;
                        break;
                }
            }
            return false;
        });
        if (ConfigHelper.getShowInterstitialPages().contains("home")) {
            AdManager.showInterstitial(requireActivity());
        }
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Update_Me_Info:
            case Constants.Event.Login_Suc:
            case Constants.Event.Login_Out:
                break;
            case Constants.Event.Config_Update:
                ClientConfig.NoticeItem marquee = ZzConfigs.getClientConf().getMarquee();
                UiHelper.setVisibleElseGone(mDataBind.marquee1Layout, marquee != null);
                if (marquee != null) {
                    mDataBind.marquee1.setText(marquee.getTitle());
                }
                updateMallRecommend();
                break;
        }
    }

    //热销商品
    private void initMallAdapter() {
        mDataBind.mallRecycler.setLayoutManager(new StaggeredGridLayoutManager(ZzConfigs.mTourismScenicRecGridNum, StaggeredGridLayoutManager.VERTICAL));
//        mDataBind.mallRecycler.setLayoutManager(new GridLayoutManager(getContext(), ZzConfigs.mTourismScenicRecGridNum));
        mDataBind.mallRecycler.setNestedScrollingEnabled(false);
        mMallAdapter = new DataBindQuickAdapter<MallRecommendBean>(ZzConfigs.mTourismMallStyle, null) {
            @Override
            protected void convert(DataBindViewHolder helper, MallRecommendBean item) {
                helper.getBinding().setVariable(BR.bean, item);
                ImageHelper.loadImage(helper.getView(R.id.image), item.getSku_img());
                if (item.getTag_energy() == 1) {
                    Bitmap bitmap = BitmapUtils.compressBitmap(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_zhyd), 47, 4);
                    ImageSpan span = new ImageSpan(getContext(), bitmap);
                    SpannableString spanStr = new SpannableString(item.getSku_name());
                    spanStr.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    ((TextView) helper.getView(R.id.tv_name)).setText(spanStr);
                } else {
                    ((TextView) helper.getView(R.id.tv_name)).setText(item.getSku_name());
                }
            }
        };
        mMallAdapter.bindToRecyclerView(mDataBind.mallRecycler);
        mMallAdapter.setLoadMoreView(new SimpleLoadMoreView());
        mMallAdapter.setEmptyView(mFieldStateLayout = new FieldStateLayout(mContext, UiHelper.dp2px(180)));
        mMallAdapter.setHeaderAndEmpty(true);
        mMallAdapter.setOnItemClickListener((adapter, view, position) -> {
            MallRecommendBean mallRecommendBean = mMallAdapter.getItem(position);
            if (mallRecommendBean == null) {
                return;
            }

            if (StringHelper.isNotEmpty(mallRecommendBean.getUrl())) {
                String product_url = mallRecommendBean.getUrl();
                Router.turnTo(mContext, YcWebViewActivity.class)
                        .putExtra(Const.Extra.Web_View_Url, product_url)
                        .putExtra(Const.Extra.Web_View_Title_Visible, false)
                        .start();
            }
            AntsAdHelper.adClicked(mallRecommendBean.getAd_id());
        });
        mFieldStateLayout.setReloadListener(click -> onLoadData());
    }

    private void initTopGrid() {
        mDataBind.gridCommon.setAdapter(new CommonAdapter<Triple<Integer, String, ConfigParent.RouterCallback>>(
                mContext, R.layout.item_tourism_portal, ZzConfigs.mTourismPortal) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, Triple<Integer, String, ConfigParent.RouterCallback> triple, int position) {
                ImageView imageView = (ImageView) baseViewHolder.getViewByViewId(R.id.iv_res);
                imageView.setImageResource(triple.getLeft());
                TextView textView = (TextView) baseViewHolder.getViewByViewId(R.id.tv_name);
                textView.setText(triple.getMiddle());
/*                // 小红点
                if (position == 5 && PrefHelper.getBoolean(Constants.Prefs.Red_Badge_5, true)) {
                    mBadgeView5 = BadgeFactory.createDot(mContext)
                        .setBadgeBackground(UiHelper.getColor(R.color.red_color))
                        .setSpace(1, 0)
                        .bind(imageView);
                }*/
            }
        });
        mDataBind.gridCommon.setOnItemClickListener((adapterView, view, i, l) -> {
            ZzConfigs.mTourismPortal.get(i).getRight().onCallBack(mContext);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        Logs.d("onActivityResult " + requestCode + resultCode + JsonHelper.toJson(data));
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == Constants.Activity_Req_Code.Scan) {
            String content = data.getStringExtra(Constant.CODED_CONTENT);
            Logs.d("scan", "获取到扫码结果 " + content);
            RouterHelper.router(getActivity(), content);
        }
    }

    @Override
    protected void onLoadData() {
        if (ZzConfigs.mIndexInfo != null) {
            updateInfo();
            RxBus.get().postEvent(Constants.Event.Config_Update);//config已经被缓存了，不会再去加载，首页也没办法收到这个变化，所有手动发送一次，用来显示marquee和notice
            mDataBind.setIsNewYear(ZzConfigs.getClientConf().isNewYear());
            return;
        }
        mFieldStateLayout.setViewState(MultiStateView.VIEW_STATE_LOADING);
        BusinessHelper.loadIndexConfig(bool -> {
            if (bool) {
                mFieldStateLayout.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                updateInfo();
            } else {
                mFieldStateLayout.setViewState(MultiStateView.VIEW_STATE_ERROR);
                showToast("网络异常，请检查网络后再试");
            }
        });
    }

    void updateInfo() {
        addSubscribe(RetrofitHelper.getApis().rateInfo()
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                    }
                }, RxHelper.getHideProgressConsumer(this)));
        // 加载banner
        initBanner(mDataBind.banner, ZzConfigs.mIndexInfo.getBanner());
        // 商品推荐
        updateMallRecommend();
        updateLive();
        if (!BuildConfig.STORE) {
            //检查更新
            AppUpdateManager.checkVersion2(getActivity(), false, ZzConfigs.mIndexInfo.getVersion());
        }
    }

    private void updateLive() {
        if (BuildConfig.STORE) {
            return;
        }
        ClientConfig.WebUrl url = ZzConfigs.getClientConf().getWeb_url().get("live_api");
        if (url == null || StringHelper.isEmpty(url.getUrl())) {
            mDataBind.liveContainer.setVisibility(View.GONE);
            return;
        }
        HttpUtil.api.liveList(ZzConfigs.getClientConf().getWeb_url().get("live_api").url + "/open/recommend", Collections.emptyMap())
                .enqueue(new Callback<Response<LiveHot>>() {
                    @Override
                    public void onResponse(Call<Response<LiveHot>> call, retrofit2.Response<Response<LiveHot>> response) {
                        if (!response.isSuccessful()) {
                            ToastUtils.showShort("" + response.message());
                            return;
                        }
                        Response<LiveHot> result = response.body();
                        if (result.getCode() != 2000) {
                            ToastUtils.showShort("" + result.getMsg());
                            return;
                        }
                        if (result.getData() == null) {
                            //"数据为空"
                            ToastUtils.showShort("数据为空");
                        }

                        LiveHot liveHot = result.getData();
                        if (CollectionHelper.isEmpty(liveHot.getList())) {
                            mDataBind.liveContainer.setVisibility(View.GONE);
                            return;
                        }
                        mDataBind.liveContainer.setVisibility(View.VISIBLE);
                        mDataBind.liveMore.setOnClickListener(v -> {
                            RouterHelper.router(getActivity(), liveHot.getWeb_url());
                        });
                        mDataBind.refreshLiveHot.setOnClickListener(v -> {
                            updateLive();
                        });
                        DataBindQuickAdapter<LiveHot.Live> adapter = new DataBindQuickAdapter<LiveHot.Live>(R.layout.tourism_live_item, liveHot.getList()) {

                            @Override
                            protected void convert(DataBindViewHolder helper, LiveHot.Live item) {
                                helper.getBinding().setVariable(BR.live, item);
                            }
                        };
                        adapter.setOnItemClickListener((adapter1, view, position) -> {
                            LiveHot.Live live = adapter.getItem(position);
                            if (!UserManager.isLogin()) {
                                UserManager.routeLogin(getContext());
                                return;
                            }
                            LiveActivity.Companion.start(getContext(), live.getLive_number(), false);
                        });
                        mDataBind.liveRecycler.setAdapter(adapter);
                    }

                    @Override
                    public void onFailure(Call<Response<LiveHot>> call, Throwable t) {

                    }
                });
        setTimeTips();
    }

    private void updateMallRecommend() {
        List<MallRecommendBean> list = ZzConfigs.mIndexInfo.getMall_recommend();
        if (CollectionHelper.isEmpty(list)) {
            return;
        }

        List<String> adIdArr = new ArrayList<>();
        for (MallRecommendBean bean : list) {
            if (bean.getAd_id() > 0) {
                adIdArr.add(String.valueOf(bean.getAd_id()));
            }
        }
        String ad_ids = TextUtils.join(",", adIdArr);
        AntsAdHelper.exposeAd(ad_ids);
        mMallAdapter.setNewData(list);
    }

    void initBanner(Banner banner, List<BannerBean> bean) {
        //设置图片加载器
        banner.setDelayTime(3000);
        banner.setImageLoader(new GlideBannerLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        if (CollectionHelper.isEmpty(bean)) {
            Integer[] slideShowArray = new Integer[]{R.drawable.slide_show1, R.drawable.slide_show2};
            //设置图片集合
            banner.setImages(Arrays.asList(slideShowArray));
        } else {
            List<String> imgs = new ArrayList<>(bean.size());
            List<String> adIdArr = new ArrayList<>();
            for (int i = 0, y = bean.size(); i < y; i++) {
                imgs.add(bean.get(i).getImg_url());
                if (bean.get(i).getAd_id() > 0) {
                    adIdArr.add(String.valueOf(bean.get(i).getAd_id()));
                }
            }
            String ad_ids = TextUtils.join(",", adIdArr);
            AntsAdHelper.exposeAd(ad_ids);

            banner.setImages(imgs);
            banner.setOnBannerListener(position -> {
                BannerBean item = bean.get(position);
                if (item.getType().equals("2")) {
                    RouterHelper.router(getActivity(), item.getUrl());
                    AntsAdHelper.adClicked(item.getAd_id());
                }
            });
        }
        banner.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mall_more:
                ZzConfigs.toWebActivityByUrl(mContext, "mall");
                break;
            case R.id.scan:
                if (PermissionsChecker.checkPermissions(getContext(), Constants.CAMERA_PHOTO2)) {
                    startScan();
                    return;
                }
                UiHelper.showConfirmDialog(getContext(), "权限申请", "需要获取“相机”权限，开启后将可以用于扫描二维码功能",
                        (dialog, which) -> {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    addSubscribe(new RxPermissions(getActivity())
                                            .request(Constants.CAMERA_PHOTO2)
                                            .subscribe(aBoolean -> {
                                                if (!aBoolean) {
                                                    showToast("没有权限，无法扫描二维码");
                                                    return;
                                                }
                                                startScan();
                                            }));
                                    break;
                                case DialogInterface.BUTTON_NEGATIVE:
                                    ToastUtils.showLong("没有权限，无法扫描二维码");
                                    break;
                            }
                        });
                break;
            case R.id.search:
//                Router.turnTo(mContext, ScenicListActivity.class)
//                        .putExtra(Constants.Extra.Scenic_Type, Constants.Scenic_Type.SetPartnerAdvance)
//                        .start();
                Router.turnTo(mContext, ScenicTabActivity.class).start();
                break;
            case R.id.marquee1:
                Dialogs.noticeAction(getActivity(), ZzConfigs.getClientConf().getMarquee());
                break;
            case R.id.marquee1_close:
                mDataBind.marquee1Layout.setVisibility(View.GONE);
                break;
            case R.id.tv_favorite:
                Router.turnTo(mContext, FragmentContainerActivity.class)
                        .checkLogin(true)
                        .putExtra(Constants.Extra.Fragment, Constants.Container.CollectBox)
                        .putExtra(Constants.Extra.Title, "收藏夹")
                        .start();
                break;
        }
    }

    private void startScan() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        /* ZxingConfig是配置类 可以设置是否显示底部布局，闪光灯，相册，*/
        ZxingConfig config = new ZxingConfig();
//                        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        // config.setShake(true);//是否震动  默认为true
        config.setDecodeBarCode(true);//是否扫描条形码 默认为true
        config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为白色
        config.setFrameLineColor(R.color.white);//设置扫描框边框颜色 默认无色
        config.setScanLineColor(R.color.white);//设置扫描线的颜色 默认白色
        config.setFullScreenScan(true);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, Constants.Activity_Req_Code.Scan);
    }

    public void setTimeTips() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH", Locale.getDefault());
        String date = sdf.format(new Date());
        int i = Integer.parseInt(date);

        if (ZzConfigs.getClientConf().isNewYear()) {
            int id = R.mipmap.img_wenhouyuone;
            if (i >= 6 && i < 9) {
                //凌晨
                id = R.mipmap.img_wenhouyuone;
            } else if (i >= 9 && i < 12) {
                //早上
                id = R.mipmap.img_wenhouyutwo;
            } else if (i >= 12 && i < 14) {
                //中午
                id = R.mipmap.img_wenhouyuthree;
            } else if (i >= 14 && i < 18) {
                //下午
                id = R.mipmap.img_wenhouyufour;
            } else if (i >= 18 && i < 24) {
                //晚上
                id = R.mipmap.img_wenhouyufive;
            } else if (i >= 0 && i <= 6) {
                //晚上
                id = R.mipmap.img_wenhouyusix;
            }
            mDataBind.timeTipsImg.setBackgroundResource(id);
        } else {
            String str = "";
            if (i >= 6 && i < 9) {
                //凌晨
                str = "Hi,早上好呀~";
            } else if (i >= 9 && i < 12) {
                //早上
                str = "Hi,上午好呀~";
            } else if (i >= 12 && i < 14) {
                //中午
                str = "Hi,中午好呀~";
            } else if (i >= 14 && i < 18) {
                //下午
                str = "Hi,下午好呀~";
            } else if (i >= 18 && i < 24) {
                //晚上
                str = "Hi,晚上好呀~";
            } else if (i >= 0 && i <= 6) {
                //晚上
                str = "夜深了，早点休息吧~";
            }
            mDataBind.timeTipsTv.setText(str);
        }
    }
}
